import { Form, Input, message, Modal, TreeSelect } from "antd";
import { useEffect, useState } from "react";
import { apiAddDict, apiDictTree, apiModifyDict } from "~/api";
import type { IDict } from "~/types/common";
import { transTreeToAntdTreeData } from "~/utils/ui.util";

interface Props {
  defaultParentId?: number;
  visible?: boolean;
  dict?: IDict | null;
  onCancel?: () => void;
  onOk?: (values: Partial<IDict>) => void;
}

export default function DictModal(props: Props) {
  const [form] = Form.useForm<Partial<IDict>>();
  const [treeData, setTreeData] = useState<IDict[]>([]);

  const _handler = {
    onCancel: () => {
      props.onCancel?.();
    },
    onOk: async () => {
      try {
        const fieldsValue = await form.validateFields();
        if (props.dict?.id) {
          await apiModifyDict(props.dict.id, fieldsValue);
        } else {
          await apiAddDict(fieldsValue);
        }
        props.onOk?.({
          id: props.dict?.id,
          ...fieldsValue,
        });
      } catch (error: any) {
        message.error({
          content: error.message,
        });
      }
    },
  };

  const _fetch = {
    init: async () => {
      const resp = await apiDictTree();
      setTreeData([
        {
          label: "~ /",
          value: 0,
          title: "根节点",
        },
        ...transTreeToAntdTreeData(
          resp.map((item) => {
            return {
              ...item,
              children: [],
            };
          }),
        ),
      ]);
    },
  };

  useEffect(() => {
    if (!props.visible) {
      return;
    }
    form.resetFields();
    if (props.defaultParentId) {
      form.setFieldValue("parentId", props.defaultParentId);
    }
    if (props.dict) {
      form.setFieldsValue(props.dict as any);
    }
  }, [props.dict, props.visible, props.defaultParentId]);

  useEffect(() => {
    _fetch.init();
  }, []);

  return (
    <Modal
      title={props.dict ? "编辑字典" : "新增子字典"}
      open={props.visible}
      maskClosable={false}
      onCancel={_handler.onCancel}
      onOk={_handler.onOk}
    >
      <Form form={form} layout={"vertical"}>
        <Form.Item label="父字典" name={"parentId"}>
          <TreeSelect
            showSearch
            placeholder="请选择父字典"
            allowClear
            treeDefaultExpandAll
            treeLine={true}
            treeData={treeData}
            treeNodeLabelProp={"label"}
            disabled={!!props.defaultParentId}
          />
        </Form.Item>
        <Form.Item label="字典名称" name={"label"} required>
          <Input />
        </Form.Item>
        <Form.Item label="字典KEY（X_XX_XXX）" name={"code"} required>
          <Input />
        </Form.Item>

        <Form.Item label="备注" name={"remark"}>
          <Input.TextArea />
        </Form.Item>
      </Form>
    </Modal>
  );
}
